package com.hue.common.utils;

import com.google.common.collect.Lists;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @Author: 姚凤桥
 * @Date: 2021/12/10 21:09
 * @Description: 发送http工具类
 */
public class HttpUtils {
    /**
     * 发送post请求，并将返回结果封装为指定类型
     *
     * @param url
     * @param params
     * @param aClass
     * @param <T>
     * @return
     */
    public static <T> T doPost(String url, MultiValueMap<String, String> params, Class<T> aClass) {
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        //以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);

        //执行HTTP请求
        try {
//            ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, aClass);
            ResponseEntity<T> response = restTemplate.postForEntity(url, requestEntity, aClass);
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 发送get请求，并将返回结果封装为指定类型
     *
     * @param url
     * @param aClass
     * @param <T>
     * @return
     */
    public static <T> T doGet(String url, Class<T> aClass) {
        RestTemplate restTemplate = new RestTemplate();

        try {
            ResponseEntity<T> response = restTemplate.getForEntity(url, aClass);
            return response.getBody();
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
//        Map<String, String> params = new HashMap<>();
//        params.put("access_token", "2.00e9OSLGVxU5CEfdbd80d3d9LBzzTD");
//        params.put("uid", "5663682184");
//        JSONObject json = HttpUtils.doGet(
//                "https://api.weibo.com/2/users/show.json?" +
//                        "access_token=2.00e9OSLGVxU5CEfdbd80d3d9LBzzTD" +
//                        "&uid=5663682184", params, JSONObject.class);
//        System.out.println(json);
    }
}
